<template>
	<custom-layout custom-class="custom-layout">
		<!-- 表单 -->
		<wd-form ref="formRef" :model="formData">
			<view class="cell-title">基本信息</view>
			<wd-cell-group border>
				<wd-picker v-model="formData.decorationType" prop="decorationType" label="装修类别"
					:columns="dictionaryStore.get('decoration_order_type')" placeholder="请选择装修类别" clearable
					:rules="[{required:true,message:'请选择装修类别'}]" />
				<wd-calendar v-model="formData.handoverTime" prop="handoverTime" label="交房时间" placeholder="请选择交房时间" />
				<wd-picker v-model="formData.houseType" prop="houseType" label="房屋类型"
					:columns="dictionaryStore.get('decoration_order_house_type')" placeholder="请选择房屋类型" clearable
					:rules="[{required:true,message:'请选择房屋类型'}]" />
				<wd-picker v-model="formData.adCode" prop="adCode" label="归属城市" :columns="cityColumns" placeholder="请选择归属城市"
					clearable :rules="[{required:true,message:'请选择归属城市'}]" value-key="adcode" label-key="name"
					:column-change="handleChangeAdCode" />
				<wd-cell title="楼盘名称" prop="propertyName" :rules="[{required:true,message:'请选择楼盘名称'}]" is-link title-width="33%"
					@click="handleOpenSelectProperty">
					<view v-if="formData.propertyName" style="text-align: start;">
						{{propertyList.find(item=>item.id===formData.propertyName)?.name}}
					</view>
					<view v-else style="text-align: start;color: #BFBFBF;">请选择楼盘名称</view>
				</wd-cell>
			</wd-cell-group>
			<view class="cell-title">客户信息</view>
			<wd-cell-group border>
				<wd-input v-model="formData.name" prop="name" label="客户名称" placeholder="请输入客户名称" clearable
					:rules="[{required:true,message:'请输入客户名称'}]" />
				<wd-input v-model="formData.phone" prop="phone" label="客户手机号" type="number" placeholder="请输入客户手机号" clearable
					:maxlength="11" :rules="[{required:true,message:'请输入客户手机号'},{pattern:/^1[3-9]\d{9}$/,message:'请输入正确的手机号'}]" />
				<wd-input v-model="formData.wxCode" prop="wxCode" label="客户微信" placeholder="请输入客户微信" clearable />
				<wd-textarea v-model="formData.address" prop="address" label="详细地址" auto-height placeholder="请输入详细地址"
					clearable />
				<wd-input v-model="formData.houseArea" prop="houseArea" label="房屋面积" type="number" placeholder="请输入房屋面积"
					clearable :rules="[{required:true,message:'请输入房屋面积'}]" />
				<wd-picker v-model="formData.sex" prop="sex" label="性别" :columns="dictionaryStore.get('system_user_sex')"
					placeholder="请选择性别" clearable />
				
			</wd-cell-group>
				
				
				
				
			
		</wd-form>
		<!-- 提交 -->
		<wd-button block size="large" custom-class="submit-button" @click="handleSubmit">提交</wd-button>
		<!-- 选择楼盘 -->
		<select-property ref="selectPropertyRef" @confirm="handleSelectProperty" />
	</custom-layout>
</template>

<script setup>
	import {
		reactive,
		ref
	} from 'vue';
	import {
		useDictionaryStore,
		useUserStore
	} from '@/store/index.js'
	import city from '@/utils/city.js'
	import {
		createClue,
		getPropertyList
	} from '@/api/clue/create.js'

	// 字典仓库
	const dictionaryStore = useDictionaryStore()
	// 用户仓库
	const userStore = useUserStore()
	// 楼盘列表
	const propertyList = ref([])
	// 获取楼盘列表
	const handleGetPropertyList = () => {
		const params = {
			pageSize: -1
		}
		getPropertyList(params).then((data) => {
			propertyList.value = data.list
		}).catch((error) => {
			uni.showToast({
				title: error,
				icon: 'error'
			})
		})
	}
	handleGetPropertyList()
	// 表单ref
	const formRef = ref()
	// 表单数据
	const formData = reactive({
		handoverTime: null
	})
	// 处理提交
	const handleSubmit = async () => {
		const validateResult = await formRef.value.validate()
		if (!validateResult.valid) return
		uni.showLoading({
			mask: true
		})
		const params = {
			...formData,
			province: formData.adCode[0],
			city: formData.adCode[1],
			area: formData.adCode[2],
			channelSource: "2",
			wxUserId: userStore.userId
		}
		createClue(params).then(() => {
			
			const templateId = 'krVt-ttUh8ddIlrXp3lbirkNRw9tFjzkZGgN8KQqlmU'; // 替换为你在微信公众平台获取的模板ID
			wx.requestSubscribeMessage({
			  tmplIds: [templateId],
			  success(res) {
			    if (res[templateId] === 'accept') {
			      // 用户同意订阅
			      console.log('用户同意订阅');
				  uni.showToast({
				  	title:'用户同意订阅',
					icon:'success'
				  })
			    } else {
			      // 用户拒绝订阅
			      console.log('用户拒绝订阅');
				  uni.showToast({
				  	title:'用户拒绝订阅',
				  	icon:'error'
				  })
			    }
			  },
			  fail(err) {
			    console.error('请求订阅失败', err);
				uni.showToast({
					title:'请求订阅失败',
					icon:'error'
				})
			  },
			  complete() {
				// 无论订阅成功或失败，都执行以下操作
				uni.navigateBack(); // 返回上一页
				uni.$emit('refresh-clue-list'); // 触发刷新线索列表
				}
			});
		}).catch((error) => {
			setTimeout(() => {
				uni.showToast({
					title: error,
					icon: 'error'
				})
			})
		}).finally(() => {
			uni.hideLoading()
			
		})
	}
	// 城市columns
	const cityColumns = ref([
		city.tree, city.tree[0].districts, city.tree[0].districts[0].districts
	])
	// 处理改变adCode
	const handleChangeAdCode = (pickerView, value, columnIndex, resolve) => {
		const empty = [{
			name: '',
			adcode: ''
		}]
		if (columnIndex === 0) {
			pickerView.setColumnData(1, value[0].districts)
			pickerView.setColumnData(2, value[0].districts[0].districts.length ? value[0].districts[0].districts : empty)
		} else if (columnIndex === 1) {
			pickerView.setColumnData(2, value[1].districts.length ? value[1].districts : empty)
		}
		resolve()
	}
	// 选择楼盘ref
	const selectPropertyRef = ref()
	// 处理打开选择楼盘
	const handleOpenSelectProperty = () => {
		selectPropertyRef.value.open()
	}
	// 处理选择楼盘
	const handleSelectProperty = (id) => {
		formData.propertyName = id
		handleGetPropertyList()
	}
</script>

<style lang="scss" scoped>
	// 自定义布局
	:deep(.custom-layout) {
		background: #F8F8F8;
	}

	// 提交按钮
	:deep(.submit-button) {
		margin: 32rpx;
	}
	.cell-title {
		font-size: 30rpx;
		font-weight: bold;
		margin: 24rpx;
		padding-left: 10rpx;
		position: relative;
	}
	.cell-title:before {
		content: "";
		position: absolute;
		left: -2px;
		top: 15%;
		height: 70%;
		width: 6rpx;
		background-color: #6a9cff;
	}
</style>